<?php
/**
 * Created by PhpStorm.
 * User: Dave
 * Date: 2018/5/26
 * Time: 14:02
 */

namespace Biz\tools;


use PhpParser\Serializer\XML;

class SmallEnergyDes
{
    private static $key = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG';

    public static function getMessage($stringDes)
    {
        $arrayDes    = self::hexStr2ByteArr($stringDes);
        $stringDes   = self::array2str($arrayDes);
        $result      = self::stringDesToArray($stringDes);
        return $result;
    }

    private static function stringDesToArray($stringDes)
    {
        $iv     = openssl_random_pseudo_bytes(openssl_cipher_iv_length('DES-ECB'));
        $object = openssl_decrypt($stringDes, 'DES-ECB', self::$key,OPENSSL_RAW_DATA, $iv);
        $result = self::xmlToarray($object);
        return $result;
    }

    private static  function xmlToarray($object)
    {
        $result = simplexml_load_string($object, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
        return json_decode(json_encode($result),1);
    }

    private static function hexStr2ByteArr($string)
    {
        $len    = strlen($string);
        $return = array();

        for($i=0;$i<$len;$i=$i+2)
        {
            $return[] = hexdec(substr($string,$i,2));
        }

        return $return;
    }

    private static  function array2str($array)
    {
        $string = '';

        foreach ($array as $key => $value){
            $string .= chr($value);
        }

        return $string;

    }

}